package com.shycloud.mido.common.security.feign;

import feign.hystrix.FallbackFactory;
import lombok.NoArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.cglib.proxy.Enhancer;

import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ConcurrentMap;

/**
 * 默认 Fallback，避免写过多fallback类
 *
 * @param <T> 泛型标记
 * @author L.cm
 */
@Slf4j
@NoArgsConstructor
public final class ShyFeignFallbackFactory<T> implements FallbackFactory<T> {
	public static final ShyFeignFallbackFactory INSTANCE = new ShyFeignFallbackFactory();
	private static final ConcurrentMap<Class<?>, Object> FALLBACK_MAP = new ConcurrentHashMap<>();

	@SuppressWarnings("unchecked")
	public T create(final Class<?> type, final Throwable cause) {
		return (T) FALLBACK_MAP.computeIfAbsent(type, key -> {
			Enhancer enhancer = new Enhancer();
			enhancer.setSuperclass(key);
			enhancer.setCallback(new ShyFeignFallbackMethod(type, cause));
			return enhancer.create();
		});
	}

	@Override
	public T create(Throwable cause) {
		return null;
	}
}
